package com.seago.iceberg.config;

import jakarta.annotation.PostConstruct;
import jakarta.persistence.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * Title:
 * <p>
 * description:
 *
 * @Company: 中国船舶集团海舟系统技术有限公司-武汉
 * @author: yangs
 * @since: 2023-05-08 11:00
 * @version: 1.0
 **/
@Component
public class EntityScanner {
	private static final String ENTITY_PACKAGE = "com.seago";

	@Autowired
	IcebergConfiguration icebergConfiguration;

	@Autowired
	private EntityRegistry entityRegistry;

	@PostConstruct
	public void scanEntities() {
		ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
		scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

		Set<BeanDefinition> entityBeanDefinitions = scanner.findCandidateComponents(icebergConfiguration.getBasePackage());

		for (BeanDefinition beanDefinition : entityBeanDefinitions) {
			try {
				Class<?> entityClass = Class.forName(beanDefinition.getBeanClassName());
				System.out.println("Found entity class: " + entityClass);
				// Do something with the entity class
				entityRegistry.registerEntity(entityClass);
			} catch (ClassNotFoundException e) {
				System.err.println("Failed to load entity class: " + beanDefinition.getBeanClassName());
			}
		}
	}
}
